package com.example.ssmlab2.controller;

import com.example.ssmlab2.model.Book;
import com.example.ssmlab2.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
@RequestMapping("book")
public class BookController extends BaseController {
    private BookService bookService;

    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @RequestMapping(value = "addBook", method = RequestMethod.POST)
    private String addBook(Book book) {
        bookService.create(book);
        List<Book> books = bookService.queryAll();
        session.setAttribute("books", books);
        return "redirect:/user/index.jsp";
    }

    @RequestMapping(value = "deleteById/{id}", method = RequestMethod.GET)
    private String deleteById(@PathVariable("id") int id) {
        bookService.remove(id);
        session.setAttribute("books", bookService.queryAll());
        return "redirect:/user/index.jsp";
    }

    @RequestMapping(value = "detailById/{id}", method = RequestMethod.GET)
    private String detailById(@PathVariable("id") int id) {
        Book book = bookService.queryById(id);
        request.setAttribute("book", book);
        return "/user/detail_book.jsp";
    }

    @RequestMapping(value = "alertById/{id}",method = RequestMethod.GET)
    private String alertById(@PathVariable("id") int id){
        request.setAttribute("book",bookService.queryById(id));
        return "/user/alert_book.jsp";
    }

    @RequestMapping(value = "updateById",method = RequestMethod.POST)
    private String updateById(Book book){
        bookService.modify("updateBookById",book);
        session.setAttribute("books", bookService.queryAll());
        return "redirect:/user/index.jsp";
    }
}
